package se.djupfeldt.oscar.logbook.console.commands;

import java.util.Arrays;

import org.apache.log4j.Logger;

public class Exit extends Command {
    
    private static Exit instance;
    private String retVal = "";
    
    public static Exit getInstance() {
	if (instance == null)
	    instance = new Exit();
	return instance;
    }

    @Override
    public String execute(String[] args) {
	if (args.length > 1)
	    return "Too many arguments.";
	else if (args.length == 0) {
	    System.out.println("Exiting.");
	    System.exit(1);
	} else {
	    return exit(args);
	}
	return "Could not execute command: Exit " + Arrays.toString(args);
    }

    private String exit(final String[] args) {
	try {
	    long delay = Integer.parseInt(args[0]) * 1000;
	    final long delayFinal = delay;
	    retVal = "Waiting " + args[0] + " s before exiting.";

	    new Thread("Exit delay thread") {
		@Override
		public void run() {
		    try {
			Thread.sleep(delayFinal);
			System.out.println("Exiting.");
			System.exit(1);
		    } catch (InterruptedException e) {
			Logger.getLogger(getClass()).error(e);
		    }
		}
	    }.start();
	} catch (NumberFormatException e) {
	    retVal = "Bad argument: " + args[0];
	}
	
	return retVal;
    }
    
    @Override
    public String help() {
        return "Exits Logbook.\nexit\nexit <delay>\t Exit Logbook after <delay> seconds.";
    }

}
